package com.security.demo.controller;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.Principal;

/**
 * 获取当前登录用户
 */
@RestController
public class GetUserController {

    /**
     * 使用 SecurityContextHolder 获取
     */
    @RequestMapping("/user/getname")
    public String getUserName() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        return auth.getName();
    }

    /**
     * 通过内置代理对象 Principal 获取
     */
    @RequestMapping("/user/getname2")
    public String getUserName2(Principal principal) {
        return principal.getName();
    }

    /**
     * 使用内置对象 Authentication 获取
     */
    @RequestMapping("/user/getname3")
    public String getUserName3(Authentication auth) {
        return auth.getName();
    }
}
